package datastructure;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-11-20 下午4:58
 */
public class Chapter6_5 {
    /**
     * 拆分红包
     * <p>
     * 假设剩余红包的金额为m,剩余人数为n,则有如下公式：
     * 每次抢到的金额=随机区间[0.01, m/n＊2-0.01]
     * 这个公式保证了每次随机金额的平均值是相等的
     *
     * @param totalAmount    　总金额（以分为单位）
     * @param totalPeopleNum 　总人数
     * @return
     */
    public static List<Integer> divideRedPackage(Integer totalAmount, Integer totalPeopleNum) {
        List<Integer> amountList = new ArrayList<>();
        Integer restAmout = totalAmount;
        Integer restPeopleNum = totalPeopleNum;
        Random random = new Random();
        for (int i = 0; i < totalPeopleNum - 1; i++) {
            //随机范围:[1,剩余人均金额的２倍-1]分
            int amount = random.nextInt(restAmout / restPeopleNum * 2 - 1) + 1;
            restAmout -= amount;
            restPeopleNum--;
            amountList.add(amount);
        }
        amountList.add(restAmout);
        return amountList;
    }

    public static void main(String[] args) {
        List<Integer> amountList = divideRedPackage(1000, 10);
        for (Integer amount : amountList) {
            System.out.println("抢到金额:" + new BigDecimal(amount).divide(new BigDecimal(100)));
        }
    }
}
